package personal.zq.practice.common.utils;

import lombok.extern.slf4j.Slf4j;

/**
 * @author za-donghao
 * @Description 适用于jdk1.7版本
 * 引入pom依赖
 * <dependency>
 *   <groupId>commons-codec</groupId>
 *   <artifactId>commons-codec</artifactId>
 *   <version>1.10</version>
 * </dependency>
 * @Date 2020/8/24 11:25
 */
@Slf4j
public class Sha256Utils {

	static final String HMAC_SHA256 = "HmacSHA256";

	/**
	 *
	 * @param key 签名key
	 * @param str 待签名字符串
	 * @return 签名后的16进制字符串
	 * @throws Exception
	 */
	/*public static String sign(String key, String str) {
		try {
			String base64Str = Base64.encodeBase64String(str.getBytes(StandardCharsets.UTF_8));
			return signByBase64(key, base64Str);

		}catch (Exception e){
			log.error("获取千里马签名失败={}",e);
		}
		throw new RuntimeException("获取千里马签名失败");
	}

	public static String signByBase64(String key, String base64Str) throws Exception {
		Mac sha256_HMAC = Mac.getInstance(HMAC_SHA256);
		SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), HMAC_SHA256);
		sha256_HMAC.init(secret_key);
		byte[] bytes = sha256_HMAC.doFinal(base64Str.getBytes());
		return bytesToHex(bytes);
	}


	private static String bytesToHex(byte[] bytes) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < bytes.length; i++) {
			String hex = Integer.toHexString(bytes[i] & 0xFF);
			if (hex.length() < 2) {
				sb.append(0);
			}
			sb.append(hex);
		}
		return sb.toString();
	}*/

}
